/**
 * Copyright (c) 2015-2020, imos.cc;
 * Author for Asher Xu (asher.xu@aliyun.com).
 */

package cc.imos.communal.kit;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;

/**
 * 数据工具类
 */
public class DataKit {

	private static final DecimalFormat DF = new DecimalFormat("#.00");
	private static final NumberFormat NF = NumberFormat.getCurrencyInstance(Locale.CHINA);

	/* ==================== | 小数 | ==================== */
	/** 保留 2位小数：进 1 法 */
	public static final String dfFormat(Double d) {
		return dfFormat(d + 0.004, null);
	}

	/** 4 舍 5 入 */
	public static final String dfFormat(Double d, String df) {
		if (StringUtils.hasText(df)) {
			DecimalFormat format = new DecimalFormat(df);
			return format.format(d);
		} else {
			return DF.format(d);
		}
	}

	/**
	 * 用于将字符串价格转换成 long 型价格
	 *
	 * @param sl
	 * @return
	 */
	public static final Long toLong(String sl) {
		if(sl.isEmpty()) {
			throw new NumberFormatException("无法解析成价格: " + sl);
		}

		boolean isNegative = sl.charAt(0) == '-';
		if(isNegative) {
			// skip '-'
			sl = sl.substring(1);
		}

		String[] values = sl.split("\\.", -2);

		if (1 == values.length) {
			// 没有小数点
			long price = 10000 * Long.valueOf(values[0]);

			return isNegative ? -price : price;
		}

		if (2 != values.length) {
			throw new NumberFormatException("无法解析成价格: " + sl);
		}

		long price = 10000 * Long.valueOf(values[0]);
		int decimalLength = values[1].length();
		long decimalPart = Long.valueOf(values[1]);

		for (int i = 0; i < 4 - decimalLength; i++) {
			decimalPart *= 10;
		}

		while (decimalPart >= 100000) {
			decimalPart /= 10;
		}
		if (decimalPart > 10000) {
			decimalPart += 5;
			decimalPart /= 10;
		}

		price += decimalPart;

		return isNegative ? -price : price;
	}

	/* ==================== | 数据格式 | ==================== */

	public static final String nfFormat(Double d) {
		return nfFormat(d, null);
	}

	public static final String nfFormat(Double d, Locale locale) {
		if (locale == null) {
			return NF.format(d);
		} else {
			NumberFormat format = NumberFormat.getCurrencyInstance(locale);
			return format.format(d);
		}
	}

	//
	public static final String reqPars(Map<String, String> map) {
		StringBuffer sb = new StringBuffer();
		for (Entry<String, String> entry : map.entrySet()) {
			sb.append("&");
			String key = entry.getKey();
			String value = entry.getValue();
			if (StringUtils.hasText(value))
				try {
					value = URLEncoder.encode(value, "UTF-8");
				} catch (UnsupportedEncodingException e) {
					throw new RuntimeException(e);
				}
			sb.append(key).append("=").append(value);
		}
		String data = sb.toString();
		data = data.replaceFirst("&", "");
		return data;
	}




	public static final ObjectMapper mapper = new ObjectMapper();
	/* ==================== | 类型转换 | ==================== */
	public static String beanToJson(Object object) {
		try {
			String result = mapper.writeValueAsString(object);
			return result;
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static <T> T jsonTobean(String json, Class<T> tClass) {
		try {
			return mapper.readValue(json, tClass);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public static <T> T beanToBean(Object object, Class<T> tClass) {
		String json = beanToJson(object);
		T t = jsonTobean(json, tClass);
		return t;
	}

}
